<?php
include("libraries/database.php");
include("libraries/sms_exception.php");

$server = "www.cic.mx";
$database = "proje105_ushahidi";
$username = "proje105_usrcic";
$password = "proyecto101"; 

$wsdl = "sms_interfaces.wsdl";

function enableService($phone)
{
	global $server, $database, $username, $password;
	
	try
	{
		// Connect to database
		$db = new Database($server, $database, $username, $password);
		
		// Add alert
		$args = array(
			"alert_type" => 1,
			"alert_recipient" => $phone,
			"alert_code" => "DEFAULT",
			"alert_confirmed" => 1,
			"alert_lat" => "25.687365916009",
			"alert_lon" => "-100.31431964459",
			"alert_radius" => 50,
			"alert_ip" => ""
		);
		$query = $db->insert("alerts", $args);
		
		foreach ($query as $queries)
		{
			$response = successfulResponse($queries->insert_id."-->ID");
		}
		// Associate categories with alert
		$categories = $db->query(
			"SELECT 
				`c`.`id` `category_id`
			FROM
				`category` `c`
			WHERE
				`c`.`id` NOT IN (SELECT 
					`c`.`parent_id`
				FROM
					`category` `c`
				WHERE
					`c`.`parent_id` > 0);"
		);
		
		foreach ($categories as $category)
		{
			$args = array(
				"alert_id" => $query->insert_id,
				"category_id" => $category->category_id
			);
			$db->insert("alert_category", $args);
		}
	}
	catch (Exception $ex)
	{
		$response = failResponse($ex->getMessage());
	}
	
	// Destroy reference to database connection
	$query = NULL;
	$db = NULL;
}

function sendReport($phone, $text)
{
	global $server, $database, $username, $password;
	
	$reporter_id = -1;
	
	// Connect to database
	$db = new Database($s, $database, $username, $password);
	
	// Add location
	$args = array(
		"location_name" => "Unknown SMS",
		"latitude" => "25.687365916009",
		"longitude" => "-100.31431964459",
		"location_visible" => 0,
		"location_date" => date("Y-m-d H:i:s", (time() + (2 * 60 * 60)))
	);
	$queryLocation = $db->insert("location", $args);

	$args = array(
		"incident_id" => NULL, 
		"location_id" => NULL, 
		"user_id" => NULL, 
		"service_id" => 1, 
		"level_id" => 3, 
		"service_userid" => NULL, 
		"service_account" => NULL, 
		"reporter_first" => NULL, 
		"reporter_last" => NULL, 
		"reporter_email" => NULL, 
		"reporter_phone" => $phone, 
		"reporter_ip" => NULL, 
		"reporter_date" => date("Y-m-d H:i:s", (time() + (2 * 60 * 60)))
	);
	$queryReporter = $db->insert("reporter", $args);	

	$args = array(
		"parent_id" => 0,
		"incident_id" => 0,
		"user_id" => 0,
		"reporter_id" => $queryReporter->insert_id,
		"service_messageid" => 1, 
		"message_from" => null, 
		"message_to" => null, 
		"message" => 'Reporte via SMS', 
		"message_detail" => $text, 
		"message_type" => 1, 
		"message_date" => date("Y-m-d H:i:s", (time() + (2 * 60 * 60))), //arreglar para jalar la hora segun timezone
		"message_level" => 0
	);
	$queryLocation = $db->insert("message", $args);
	
	// Add incident
	/*$args = array(
		"location_id" => $queryLocation->insert_id,
		"form_id" => 1,
		"locale" => "es_MX",
		"user_id" => 1,
		"incident_title" => "Reporte via SMS",
		"incident_description" => $text,
		"incident_date" => date("Y-m-d H:i:s"),
		"incident_mode" => 4,
		"incident_active" => 1,
		"incident_verified" => 1,
		"incident_source" => 1,
		"incident_rating" => 0,
		"incident_dateadd" => date("Y-m-d H:i:s"),
		"incident_alert_status" => 0
	);*/
	//$queryIncident = $db->insert("incident", $args);
	
	// Associate categories with incident
	$categories = $db->query(
		"SELECT 
			`c`.`id` `category_id`
		FROM
			`category` `c`
		WHERE
			`c`.`id` NOT IN (SELECT 
				`c`.`parent_id`
			FROM
				`category` `c`
			WHERE
				`c`.`parent_id` > 0);"
	);
	
	foreach ($categories as $category)
	{
		$args = array(
			"incident_id" => $queryIncident->insert_id,
			"category_id" => $category->category_id
		);
		$db->insert("incident_category", $args);
	}
	
	// Destroy reference to database connection
	$queryLocation = NULL;
	$queryIncident = NULL;
	$db = NULL;
}

function successfulResponse($text)
{
	// Create a successful response
	$dom = new DOMDocument();
	
	$smsOut = $dom->createElement("smsout");
	//$response = $dom->createElement("respuesta", "OK");
	$response = $dom->createElement("respuesta", $text);
	$smsOut->appendChild($response);
	$dom->appendChild($smsOut);
	
	return $dom->saveXML();
}

function failResponse($errorMessage)
{
	// Create a error response
	$dom = new DOMDocument();
	
	$smsOut = $dom->createElement("smsout");
	$response = $dom->createElement("respuesta", "ERROR: ".$errorMessage);
	$smsOut->appendChild($response);
	$dom->appendChild($smsOut);
	
	return $dom->saveXML();
}

function SMSConfEnvio($codeXML)
{
	global $server, $database, $username, $password;
	
	$response = "";
	$db = NULL;

	try
	{
		// Connect to database
		$db = new Database($s, $database, $username, $password);
		
		$dom = new DOMDocument();
		$dom->loadXML($codeXML);
		
		// Get info from message
		$messageId = intval($dom->getElementsByTagName("idmsj")->item(0)->nodeValue);
		$phones = explode(",", $dom->getElementsByTagName("telefono")->item(0)->nodeValue);
		$status = explode(",", $dom->getElementsByTagName("confirmacion")->item(0)->nodeValue);
		
		// Has data the XML
		if ($messageId === 0)
		{
			throw new SMSException("No se ha encontrado contenido dentro del XML");
		}
		
		// Save info in log
		for ($index = 0; $index < count($phones); $index++)
		{
			$args = array(
				"log_message_id" => $messageId,
				"log_phone_number" => $phones[$index],
				"log_status" => $status[$index]
			);
			
			$db->insert("logs", $args);
		}
		
		// Diagnostic purpose
		$dom->save("../logs/conf".$messageId.".xml");

		$response = successfulResponse("ok conf");
	}
	catch (Exception $ex)
	{
		$response = failResponse($ex->getMessage());
	}
	
	// Destroy reference to database connection
	$db = NULL;
	
	return $response;
}

function SMSEvento($codeXML)
{
	$response = "";
	$dom = NULL;

	try
	{
		$dom = new DOMDocument();
		$dom->loadXML($codeXML);
		
		// Get info from message
		$messageId = intval($dom->getElementsByTagName("idmsj")->item(0)->nodeValue);
		$phone = $dom->getElementsByTagName("telefono")->item(0)->nodeValue;
		$text = strtoupper($dom->getElementsByTagName("texto")->item(0)->nodeValue);
		
		// Verify the event
		if (trim($text) == "ALTA")
		{
			enableService($phone);
		}
		else
		{
			//sendReport($phone, $text);
			sendReport('', $text);
		}
		
		// Diagnostic purpose
		$dom->save("../logs/event".$messageId.".xml");
		
		//$response = successfulResponse($paso);
	}
	catch (Exception $ex)
	{
		$response = failResponse($ex->getMessage());
	}
	
	// Diagnostic purpose
	$dom = new DOMDocument();
	$dom->loadXML($response);
	$dom->save("../logs/eventResponse.xml");
	
	return $response;
}

//Implementacion para CityVox
function successfulRec($text)
{
	// Create a successful response
	$dom = new DOMDocument();
	
	$recOut = $dom->createElement("recout");
	//$response = $dom->createElement("respuesta", "OK");
	$response = $dom->createElement("incident_id", $text);
	$recOut->appendChild($response);
	$dom->appendChild($recOut);
	
	return $dom->saveXML();
}

function failRec($errorMessage)
{
	// Create a error response
	$dom = new DOMDocument();
	
	$recOut = $dom->createElement("recOut");
	$response = $dom->createElement("incident", "ERROR: ".$errorMessage);
	$recOut->appendChild($response);
	$dom->appendChild($recOut);
	
	return $dom->saveXML();
}

function saveReport($codeXML)
{
	global $server, $database, $username, $password;
	
	$cadena = '';
	$datos_incident_title = $cadena;
	$datos_incident_description = $cadena;
	$datos_latitude = $cadena;
	$datos_longitude = $cadena;
	$datos_location_name = $cadena;
	$datos_incident_id = $cadena;
	$datos_incident_date = $cadena;
	$datos_incident_hour = $cadena;
	$datos_incident_hour .= $cadena;
	$datos_incident_hour .= $cadena;
	$datos_incident_category = $cadena;
	$datos_desc = $cadena;
	$datos_incident_active = $cadena;
	$datos_incident_status = $cadena;
	$datos_incident_ticket = $cadena;
	$datos_incident_media = $cadena;
	$datos_person_first = $cadena;
	$datos_person_last = $cadena;
	$datos_person_email = $cadena;
	
	$campo = 0;
	$char = '';
	// $codeXML = str_replace('[', '', $codeXML);
	// $codeXML = str_replace(']', '', $codeXML);
	// $codeXML = str_replace('"', '', $codeXML);
	
	for ($index = 0; $index < strlen($codeXML); $index++)
	{
		$char = substr($codeXML, $index, 1); 
		if ($char == '|')
		{
			switch($campo)
			{
				case 0:
					$datos_incident_title = $cadena;
					break;
				case 1:
					$datos_incident_description = $cadena;
					break;
				case 2:
					$datos_latitude = $cadena;
					break;
				case 3:
					$datos_longitude = $cadena;
					break;
				case 4:
					$datos_location_name = $cadena;
					list($calle, $colonia, $municipio, $estado, $pais) = explode(",", $datos_location_name);
					break;
				case 6:
					$datos_incident_id = $cadena;
					break;
				case 9:
					$datos_incident_date = $cadena;
					break;
				case 10:
					$datos_incident_hour = $cadena.':';
					break;
				case 11:
					$datos_incident_hour .= $cadena;
					break;
				case 12:
					$datos_incident_hour .= $cadena;
					break;
				case 13:
					$cadena = str_replace('[', '', $cadena);
					$cadena = str_replace('[', '', $cadena);
					$cadena = str_replace('"', '', $cadena);
					list($datos_incident_category, $datos_desc) = explode(',', $cadena);
					break;
				case 14:
					$datos_incident_active = $cadena;
					break;
				case 15:
					$datos_incident_status = $cadena;
					break;
				case 16:
					$datos_incident_ticket = $cadena;
					break;
				case 17:
					$cadena = str_replace('[', '', $cadena);
					$cadena = str_replace('"', '', $cadena);
					$cadena = str_replace(']]', '|', $cadena);
					$cadena = str_replace(']', '|', $cadena);
					$cadena = str_replace('|,', '|', $cadena);
					$datos_incident_media = explode('|', $cadena);
					break;
				case 18:
					$datos_person_first = $cadena;
					break;
				case 19:
					$datos_person_last = $cadena;
					break;
				case 20:
					$datos_person_email = $cadena;
					break;
				case 22:
					$datos_detalle_ubicacion = $cadena;
					break;
				default:
					$cadena = '';
					break;
			}
			$campo = $campo + 1;
			$cadena = '';
		}
		else
		{
			$cadena.= $char;
		}
	}
	
	$reporter_id = -1;
	$response = "";

	// Connect to database
	$db = new Database($s, $database, $username, $password);

	if ((int)$datos_incident_id == 0)
	{
		try
		{
			// Add location
			$args = array
			(
				"location_name" => $datos_detalle_ubicacion,
				"latitude" => $datos_latitude,
				"longitude" => $datos_longitude,
				"location_visible" => 1,
				"location_date" => date("Y-m-d H:i:s", strtotime($datos_incident_date.' '.$datos_incident_hour)),
				"street_number" => $calle,
				"neihborhood" => $colonia,
				"county" => $municipio,
				"state" => $estado,
				"country" => $pais
			);
			$queryLocation = $db->insert("location", $args);
			
			$location_id = $queryLocation->insert_id;
			
			// Add incident
			$args = array(
				"location_id" => $queryLocation->insert_id,
				"form_id" => 1,
				"locale" => "es_MX",
				"user_id" => 1,
				"incident_title" => (trim($datos_incident_title) != "") ? $datos_incident_title : "Reporte via CitiVox",
				"incident_description" => $datos_incident_description,
				"incident_date" => date("Y-m-d H:i:s", strtotime($datos_incident_date.' '.$datos_incident_hour)),
				"incident_mode" => 4,
				"incident_active" => $datos_incident_active,
				"incident_verified" => 1,
				"incident_source" => 1,
				"incident_information" => NULL,
				"incident_rating" => 0,
				"incident_dateadd" => date("Y-m-d H:i:s", strtotime($datos_incident_date.' '.$datos_incident_hour)),
				"incident_alert_status" => 1,
				"incident_zoom" => 13,
				"incident_status" => $datos_incident_status,
				"incident_ticket" => $datos_incident_ticket
			);
			$queryIncident = $db->insert("incident", $args);

			$incident_id = $queryIncident->insert_id;
			
			$args = array(
				"incident_id" => $incident_id, 
				"location_id" => $location_id, 
				"user_id" => NULL, 
				"service_id" => 1, 
				"level_id" => 3, 
				"service_userid" => NULL, 
				"service_account" => NULL, 
				"reporter_first" => NULL, 
				"reporter_last" => NULL, 
				"reporter_email" => NULL, 
				"reporter_phone" => NULL, 
				"reporter_ip" => NULL, 
				"reporter_date" => date("Y-m-d H:i:s", (time() + (2 * 60 * 60)))
			);
			$queryReporter = $db->insert("reporter", $args);
			
			$args = array(
				"location_id" => $location_id,
				"incident_id" => $incident_id,
				"person_first" => $datos_person_first,
				"person_last" => $datos_person_last,
				"person_email" => $datos_person_email,
				"person_date" => date("Y-m-d H:i:s", (time() + (2 * 60 * 60)))
			);
			$queryPerson = $db->insert("incident_person", $args);
			
			$m_type = '';
			$m_link = '';
			if (is_array($datos_incident_media))
			{
				foreach ($datos_incident_media as $media)
				{
					list($m_type, $m_link) = explode(',', $media);

					if (trim($m_link) != '')
					{
						$args = array(
							"location_id" => $location_id,
							"incident_id" => $incident_id,
							"media_type" => $m_type,
							"media_link" => $m_link,
							"media_date" => date("Y-m-d H:i:s", (time() + (2 * 60 * 60))),
							"media_active" => 1
						);
						$queryMedia = $db->insert("media", $args);
						$queryMedia = NULL;
					}
				}
			}
			// Associate categories with incident
			// $categories = $db->query(
				// "SELECT 
					// `c`.`id` `category_id`, `c`.`category_title`
				// FROM
					// `category` `c`;"
			// );
			
			// foreach ($categories as $category)
			// {
				// if ($category->category_title == $datos_incident_category)
				// {
					// $args = array(
						// "incident_id" => $incident_id,
						// "category_id" => $category->category_id
					// );
					// $db->insert("incident_category", $args);
					// exit;
				// }
			// }
		}
		catch (Exception $ex)
		{
			$response = failRec($ex->getMessage());
		}
		
		// Destroy reference to database connection
		$queryLocation = NULL;
		$queryIncident = NULL;
		$queryMedia = NULL;
		$queryReporter = NULL;
		$db = NULL;
		
		if ($response != '')
		{
			return '{"incident_id":"-1", "error":"'.$response.'"}';
		}
		else
		{
			return '{"incident_id":"'.$incident_id.'", "error":"0"}';
		}
		
	}
	else
	{
		// Update incident
		try
		{
			$query = 'UPDATE `incident` SET ';
			$query .= '`incident_title` = "'.$datos_incident_title.'", ';
			$query .= '`incident_description` = "'.$datos_incident_description.'", ';
			$query .= '`incident_date` = "'.date("Y-m-d H:i:s", strtotime($datos_incident_date.' '.$datos_incident_hour)).'", ';
			$query .= '`incident_datemodify` = "'.date("Y-m-d H:i:s", (time() + (2 * 60 * 60))).'", ';
			$query .= '`incident_active` = '.$datos_incident_active.', ';
			$query .= '`incident_status` = '.$datos_incident_status.', ';
			$query .= '`incident_ticket` = '.$datos_incident_status.' ';
			$query .= 'WHERE `id` = '.$datos_incident_id.';';
		
			$update = $db->update($query);

			$update = NULL;
			// Add location
			$location = $db->query(
				"SELECT 
					`c`.`location_id`
				FROM
					`incident` `c`
				WHERE `c`.`id` = ".$datos_incident_id.";"
			);
			
			foreach ($location as $locationid)
			{
				$location_id = $locationid->location_id;
				
				$query = 'UPDATE `location` SET ';
				$query .= '`location_name` = "'.$datos_incident_title.'", ';
				$query .= '`latitude` = '.$datos_latitude.', ';
				$query .= '`longitude` = '.$datos_longitude.', ';
				$query .= '`location_date` = "'.date("Y-m-d H:i:s", strtotime($datos_incident_date.' '.$datos_incident_hour)).'", ';
				$query .= '`street_number` = "'.$calle.'", ';
				$query .= '`neihborhood` = "'.$colonia.'", ';
				$query .= '`county` = "'.$municipio.'", ';
				$query .= '`state` = "'.$estado.'", ';
				$query .= '`country` = "'.$pais.'" ';
				$query .= 'WHERE `id` = '.$location_id.';';
				
				$update = $db->update($query);
			}
			
			$update = NULL;
			$m_type = '';
			$m_link = '';
			
			if (is_array($datos_incident_media))
			{
				$query = 'DELETE FROM `media` WHERE `incident_id` = '.$datos_incident_id.' AND `location_id` = '.$location_id.'; ';
				$update = $db->update($query);
				foreach ($datos_incident_media as $media)
				{
					list($m_type, $m_link) = explode(',', $media);
					if (trim($m_link) != '')
					{
						$args = array(
							"location_id" => $location_id,
							"incident_id" => $datos_incident_id,
							"media_type" => $m_type,
							"media_link" => $m_link,
							"media_date" => date("Y-m-d H:i:s", (time() + (2 * 60 * 60))),
							"media_active" => 1
						);
						$queryMedia = $db->insert("media", $args);
						$queryMedia = NULL;
					}
				}
			}
		}
		catch (Exception $ex)
		{
			$response = failRec($ex->getMessage());
			return $response;
		}
		
		// Destroy reference to database connection
		$update = NULL;
		$db = NULL;
		
		return '{"incident_id":"'.$datos_incident_id.'", "error":"0"}';
		
	}
	
}

function recReport($codeXML)
{
	$response = "-1";

	try
	{	
		$response = saveReport($codeXML);
	}
	catch (Exception $ex)
	{
		$response = failRec($ex->getMessage());
		$response = '{"incident_id":"-2", "error":"'.$response.'"}';
	}
	
	return $response;
}


// Handle SOAP calls
$server = new SoapServer($wsdl);
$server->addFunction(array("SMSConfEnvio", "SMSEvento", "recReport"));
$server->handle();
?>